<template>
  <div>
    <li>
      <label>
        <input type="checkbox" :checked="todo.done" @change="handleChange(todo.id)">

        <!--        不建议使用 违反了props只读原则-->
        <!--        <input type="checkbox" :checked="todo.done" @click="todo.done=!todo.done"/>-->
        <!--        <input type="checkbox" v-model="todo.done"/>-->

        <span v-show="!todo.isEdit">{{ todo.title }}</span>
        <input v-show="todo.isEdit" :value="todo.title" @blur="handleEdit(todo,$event)" ref="myInput">
      </label>
      <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
      <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleToEdit(todo)">编辑</button>
    </li>

  </div>
</template>

<script>
import pubsub from 'pubsub-js'

export default {
  name: "Item",
  props: {
    todo: Object,
  },
  methods: {
    handleChange(id) {
      //全局事件总线
      // this.$bus.$emit('changeItem',id)

      //消息发布
      pubsub.publish('changeItem', id)

    },
    handleDelete(id) {
      if (confirm('删除？')) {
        // 全局事件总线
        // this.$bus.$emit('handleDel',id)

        //pubsub
        pubsub.publish('handleDel', id)

      }
    },
    handleToEdit(todo) {
      if (Object.prototype.hasOwnProperty.call(todo, 'isEdit')) {
        todo.isEdit = true
      } else {
        this.$set(todo, 'isEdit', true)
      }
      // 下一次模板解析后执行
      this.$nextTick(function () {
        this.$refs.myInput.focus()
      })

    },
    handleEdit(todo, e) {
      if (!e.target.value.trim()) {
        return alert('修改不能为空')
      } else {
        todo.isEdit = false
        this.$bus.$emit('handleEdit', todo.id, e.target.value)
      }
    },
  }
}
</script>

<style scoped>

/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:hover {
  background-color: #cccccc;
}

li:hover button {
  display: block;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

</style>
